package cn.yangliu.jwt.handler;

import cn.yangliu.jwt.tools.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 杨柳
 * @date 2019-04-18
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler,IHandler {

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String jwtToken = jwtTokenUtils.generateToken(userDetails);
        jwtTokenUtils.setExpire(jwtToken,userDetails.getUsername(),expiration);
        handle(request,response,null, HttpStatus.OK,"登录成功",jwtToken);
    }

}
